package com.hsc.www.redis.server;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import server.reids.RedisUtil;
import server.user.User;

import java.util.Collection;
import java.util.HashSet;

@Component
public class MyRedisUserDetailsService implements UserDetailsService {

    private RedisTemplate redisTemplate;

    public MyRedisUserDetailsService(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user =(User)redisTemplate.opsForValue().get(RedisUtil.createKey("t_user",username));

        if (user ==null){
            throw new UsernameNotFoundException("用户名不存在！");
        }

        Collection<SimpleGrantedAuthority> simpleGrantedAuthorityCollection=new HashSet<>();
        for (String role: user.getRoles()) {
            simpleGrantedAuthorityCollection.add(new SimpleGrantedAuthority(role));
        }

        UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), simpleGrantedAuthorityCollection);

        return  userDetails;
    }
}
